'use client';

import type {
  IComment,
  IPagination,
  IParentReply,
  IQueryParams,
  IQueryPostDetails,
} from '@/interfaces';
import Box from '@/app/[locale]/admin/common/box';
import { formatDateTime } from '@/lib/tool';
import { type ChangeEvent, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  searchParentReply,
  serverQueryAllParentReplyByReplyId,
} from '@/services/api';
import Pagination from '@/app/[locale]/admin/common/pagination';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { useRouter } from 'next/navigation';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function ParentReplyReplyAdminPage(
  this: any,
  {
    rid,
    cid,
    source,
    replies,
    translatedFields,
  }: {
    rid: string;
    cid: string;
    source: IQueryPostDetails;
    replies: IPagination<IParentReply>;
    translatedFields: PrefixedTTranslatedFields<'replyAdminPage'>;
  },
) {
  const [searchName, setSearchName] = useState('');
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
  });
  const router = useRouter();

  const serverQueryAllParentReplyByReplyIdQuery = useQuery(
    ['/forum', '/replies', '/server', rid, '/parent', params, searchName],
    async (context) => {
      if (searchName) {
        return (await searchParentReply({
          query: {
            ...(context.queryKey[5] as any),
            name: context.queryKey[6],
          },
        })) as IPagination<IParentReply>;
      } else {
        return (await serverQueryAllParentReplyByReplyId({
          id: context.queryKey[3] + '',
          query: context.queryKey[5] as any,
        })) as IPagination<IParentReply>;
      }
    },
    {
      keepPreviousData: true,
      initialData: replies,
    },
  );

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value.trim();
    setSearchName(value.toLowerCase());
  }

  function onClickPrevious() {
    const data = serverQueryAllParentReplyByReplyIdQuery.data;
    if (!data) {
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = serverQueryAllParentReplyByReplyIdQuery.data;
    if (!data) {
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onClickDetail(item: IComment) {
    router.push(
      `child-reply?pid=${source.basic.id}&cid=${cid}&rid=${rid}&prid=${item.id}`,
    );
  }

  function onClickUpdateReviewState(item: IComment) {
    router.push(
      `parent-reply/review-state?id=${item.id}&review-state=${item.reviewState}`,
    );
  }

  return (
    <Box>
      <div className="row">
        <div className="col vstack gap-4">
          <div className="card">
            <div className="card-header bg-transparent">
              <div className="row row-cols-auto justify-content-between g-2">
                <div className="col w-100">
                  <div className="input-group">
                    <span className="input-group-text">
                      <i className="bi bi-search"></i>
                    </span>
                    <input
                      onChange={onChangeSearch}
                      type="search"
                      className="form-control"
                      placeholder={translatedFields.tip.searchPlaceholder}
                    />
                  </div>
                </div>
              </div>
            </div>
            <div className="card-body">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="">
                        ID
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.content}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.state}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.author}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.time}
                      </th>
                      <th scope="col" className=""></th>
                    </tr>
                  </thead>
                  <tbody>
                    {serverQueryAllParentReplyByReplyIdQuery.data.content.map(
                      (item) => {
                        return (
                          <tr key={item.id} className="text-nowrap">
                            <td
                              className="cursor-pointer"
                              onClick={onClickDetail.bind(this, item)}
                            >
                              {item.id}
                            </td>
                            <td
                              className="cursor-pointer"
                              onClick={onClickDetail.bind(this, item)}
                            >
                              <div
                                dangerouslySetInnerHTML={{
                                  __html: item.content,
                                }}
                              />
                            </td>
                            <td
                              className="cursor-pointer"
                              onClick={onClickDetail.bind(this, item)}
                            >
                              {
                                translatedFields.enums.reviewState[
                                  item.reviewState
                                ]
                              }
                            </td>
                            <td
                              className="cursor-pointer"
                              onClick={onClickDetail.bind(this, item)}
                            >
                              {item.creatorAlias}&nbsp;(ID. {item.createdBy})
                            </td>
                            <td
                              className="cursor-pointer"
                              onClick={onClickDetail.bind(this, item)}
                            >
                              <time dateTime={item.createdOn}>
                                {formatDateTime(item.createdOn)}
                              </time>
                            </td>
                            <td>
                              <div className="hstack gap-2">
                                <button
                                  onClick={onClickUpdateReviewState.bind(
                                    this,
                                    item,
                                  )}
                                  className="btn btn-sm btn-light"
                                  type="button"
                                >
                                  <i className="bi bi-pencil me-2"></i>
                                  {translatedFields.operate.update}
                                </button>
                              </div>
                            </td>
                          </tr>
                        );
                      },
                    )}
                  </tbody>
                </table>
              </div>

              {serverQueryAllParentReplyByReplyIdQuery.data.content.length ===
                0 && <Nodata />}

              <Pagination
                isShow={
                  serverQueryAllParentReplyByReplyIdQuery.data.pageable.pages >
                  0
                }
                onPrevious={onClickPrevious}
                onNext={onClickNext}
                isPrevious={
                  serverQueryAllParentReplyByReplyIdQuery.data.pageable.previous
                }
                isNext={
                  serverQueryAllParentReplyByReplyIdQuery.data.pageable.next
                }
                translatedFields={translatedFields.pagination}
              />
            </div>
          </div>
        </div>
      </div>
    </Box>
  );
}
